package com.pla.clipboardimagepublisher;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.prefs.Preferences;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.wonderly.awt.Packer;

public class PreferencesDialog extends JDialog {
  private static final long serialVersionUID = -2027623666122469756L;
  public static final String HOST_NAME = "hostName";
  public static final String SERVLET_PATH = "servletPath";
  public static final String PICTURE_PATH = "picturePath";

  public PreferencesDialog(JFrame owner) {
    super(owner, true);
    JPanel panel = new JPanel();
    Packer packer = new Packer(panel);
    int y = 0;
    packer.add(new JLabel("Host")).gridx(0).gridy(y);
    final JTextField hostNameField = new JTextField(25);
    final Preferences preferences = Preferences.userNodeForPackage(this.getClass());
    hostNameField.setText(preferences.get(HOST_NAME, "patrickarchibald.com"));
    packer.add(hostNameField).gridx(1).gridy(y++);
    final JTextField servletPathField = new JTextField(25);
    packer.add(new JLabel("Servlet path")).gridx(0).gridy(y);
    packer.add(servletPathField).gridx(1).gridy(y++);
    servletPathField.setText(preferences.get(SERVLET_PATH,
        "/servlet/com.pla.ClipboardImagePublisherServlet"));
    packer.add(new JLabel("Picture path")).gridx(0).gridy(y);
    final JTextField picturePathField = new JTextField(25);
    picturePathField.setText(preferences.get(PICTURE_PATH, "/pictures/"));
    packer.add(picturePathField).gridx(1).gridy(y++);
    JButton saveButton = new JButton("Save");
    JButton cancelButton = new JButton("Cancel");
    packer.add(saveButton).gridx(0).gridy(y);
    packer.add(cancelButton).gridx(1).gridy(y++);
    cancelButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        setVisible(false);
        dispose();
      }
    });
    saveButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        preferences.put(HOST_NAME, hostNameField.getText());
        preferences.put(SERVLET_PATH, servletPathField.getText());
        preferences.put(PICTURE_PATH, picturePathField.getText());
        setVisible(false);
        dispose();
      }
    });
    setContentPane(panel);
    pack();
    setLocationRelativeTo(owner);
    setVisible(true);
  }

  public static void main(String[] args) {
    new PreferencesDialog(new JFrame());
  }
}
